'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egddddg';
  }
  async agree() {
    try{
      const {id} = this.ctx.request.body
      const result = await this.service.home.agree(id)
      this.ctx.response.body = result

    }catch(e) {
      this.ctx.response.body = {
        code: 0,
        msg: e.message
      }
    }
  }
  async setComment() {
    try {
      // 发帖
      // 第一步，解析出是谁，是谁要发帖
      const token = this.ctx.cookies.get('token')
      const { comment } = this.ctx.request.body
      let name = ''
      this.app.jwt.verify(token, this.app.config.jwt.secret, (err, decoded) => {
        if (err) { // 如果有错误，也就是解密失败
          // 过期，或者token不存在的时候
          throw(err)
        } else {
          console.log('解密', decoded)
          name = decoded.name
        }
      })
      const result = await this.service.home.setComment({
        comment,
        name
      })
      this.ctx.response.body = result
    } catch(e) {
      this.ctx.response.body = {
        code: 0,
        msg: e.message
      }
    }
  }

  async login() {
    try {
      const {name, password} = this.ctx.request.body
      const result = await this.service.home.login({
        name, password
      })
      this.ctx.response.body = result
    } catch(e) {
      this.ctx.response.body = {
        code: 0,
        msg: e.message
      }
    }
  }

  async list() {
    try {
      const result = await this.service.home.list()
      this.ctx.response.body = result
    } catch(e) {
      this.ctx.response.body = {
        code: 0,
        msg: e.message
      }
    }
  }
}

module.exports = HomeController;
